/**
 * DataPlexus 数据源管理综合测试运行器
 * 整合所有测试并生成最终报告
 */

import { message } from 'antd';
import DataSourceIntegrationTest from './datasourceIntegrationTest';
import ThemeAdaptationTest from './themeAdaptationTest';
import { DataSourceTestUtils } from '../utils/datasourceTestUtils';

/**
 * 综合测试运行器
 */
export class ComprehensiveTestRunner {
  private integrationTest: DataSourceIntegrationTest;
  private themeTest: ThemeAdaptationTest;
  private utilsTest: typeof DataSourceTestUtils;

  constructor() {
    this.integrationTest = new DataSourceIntegrationTest();
    this.themeTest = new ThemeAdaptationTest();
    this.utilsTest = DataSourceTestUtils;
  }

  /**
   * 运行所有测试套件
   */
  async runAllTestSuites(): Promise<{
    overall_success: boolean;
    test_suites: {
      integration: any;
      theme: any;
      utils: any;
    };
    summary: {
      total_tests: number;
      passed_tests: number;
      failed_tests: number;
      success_rate: number;
      total_duration: number;
    };
    recommendations: string[];
    final_report: string;
  }> {
    console.log('🚀 开始运行DataPlexus数据源管理综合测试套件...');
    
    const overallStartTime = performance.now();
    const testResults = {
      integration: null as any,
      theme: null as any,
      utils: null as any
    };

    try {
      // 1. 运行集成测试
      console.log('\n📋 第1阶段：前端集成测试');
      console.log('='.repeat(50));
      testResults.integration = await this.integrationTest.runAllTests();
      
      await new Promise(resolve => setTimeout(resolve, 500));

      // 2. 运行主题适配测试
      console.log('\n🎨 第2阶段：主题适配测试');
      console.log('='.repeat(50));
      testResults.theme = await this.themeTest.runAllTests();
      
      await new Promise(resolve => setTimeout(resolve, 500));

      // 3. 运行工具测试
      console.log('\n🔧 第3阶段：工具功能测试');
      console.log('='.repeat(50));
      testResults.utils = await this.utilsTest.runAllTests();

      const totalDuration = performance.now() - overallStartTime;

      // 计算总体统计
      const summary = this.calculateSummary(testResults, totalDuration);
      
      // 生成建议
      const recommendations = this.generateRecommendations(testResults);
      
      // 生成最终报告
      const finalReport = this.generateFinalReport(testResults, summary, recommendations);
      
      const overallSuccess = summary.success_rate >= 90; // 90%以上通过率视为成功

      console.log('\n' + '='.repeat(80));
      console.log('🎯 DataPlexus 数据源管理综合测试完成');
      console.log('='.repeat(80));
      console.log(`总体状态: ${overallSuccess ? '✅ 成功' : '⚠️ 需要改进'}`);
      console.log(`测试通过率: ${summary.success_rate.toFixed(1)}%`);
      console.log(`总耗时: ${(summary.total_duration / 1000).toFixed(2)}秒`);
      console.log('='.repeat(80));

      if (overallSuccess) {
        message.success(`综合测试通过！通过率: ${summary.success_rate.toFixed(1)}%`);
      } else {
        message.warning(`综合测试完成，通过率: ${summary.success_rate.toFixed(1)}%，请查看详细报告`);
      }

      return {
        overall_success: overallSuccess,
        test_suites: testResults,
        summary,
        recommendations,
        final_report: finalReport
      };

    } catch (error: any) {
      console.error('❌ 综合测试执行失败:', error);
      message.error('综合测试执行失败，请检查控制台');
      
      throw new Error(`综合测试执行失败: ${error.message}`);
    }
  }

  /**
   * 计算测试总结
   */
  private calculateSummary(testResults: any, totalDuration: number) {
    let totalTests = 0;
    let passedTests = 0;
    let failedTests = 0;

    // 集成测试统计
    if (testResults.integration) {
      totalTests += testResults.integration.total;
      passedTests += testResults.integration.passed;
      failedTests += testResults.integration.failed;
    }

    // 主题测试统计
    if (testResults.theme) {
      totalTests += testResults.theme.total;
      passedTests += testResults.theme.passed;
      failedTests += testResults.theme.failed;
    }

    // 工具测试统计
    if (testResults.utils) {
      totalTests += testResults.utils.total;
      passedTests += testResults.utils.passed;
      failedTests += testResults.utils.failed;
    }

    const successRate = totalTests > 0 ? (passedTests / totalTests) * 100 : 0;

    return {
      total_tests: totalTests,
      passed_tests: passedTests,
      failed_tests: failedTests,
      success_rate: successRate,
      total_duration: totalDuration
    };
  }

  /**
   * 生成改进建议
   */
  private generateRecommendations(testResults: any): string[] {
    const recommendations: string[] = [];

    // 基于集成测试结果的建议
    if (testResults.integration && testResults.integration.success_rate < 100) {
      const failedTests = testResults.integration.results.filter((r: any) => !r.success);
      
      failedTests.forEach((test: any) => {
        switch (test.name) {
          case 'API连接测试':
            recommendations.push('🔗 检查后端服务是否正常运行，确保API端点可访问');
            break;
          case '组件渲染性能测试':
            recommendations.push('⚡ 优化组件渲染性能，减少不必要的重新渲染');
            break;
          case '搜索防抖功能测试':
            recommendations.push('🔍 检查搜索防抖实现，确保300ms延迟正确工作');
            break;
          case 'requestGuard防重复请求测试':
            recommendations.push('🛡️ 检查requestGuard配置，确保防重复请求机制正常');
            break;
          case '表单验证功能测试':
            recommendations.push('📝 完善表单验证规则，提高用户输入体验');
            break;
          case 'TypeScript类型定义测试':
            recommendations.push('🔧 检查TypeScript类型定义，确保类型安全');
            break;
        }
      });
    }

    // 基于主题测试结果的建议
    if (testResults.theme && testResults.theme.success_rate < 100) {
      const failedThemeTests = testResults.theme.results.filter((r: any) => !r.success);
      
      if (failedThemeTests.some((t: any) => t.test_name.includes('对比度'))) {
        recommendations.push('🎨 调整主题色彩配置，提高文本和背景的对比度');
      }
      
      if (failedThemeTests.some((t: any) => t.test_name.includes('深色主题'))) {
        recommendations.push('🌙 优化深色主题下的元素可见性');
      }
      
      if (failedThemeTests.some((t: any) => t.test_name.includes('响应式'))) {
        recommendations.push('📱 改进响应式设计，确保在所有设备上正常显示');
      }
      
      if (failedThemeTests.some((t: any) => t.test_name.includes('切换'))) {
        recommendations.push('🔄 修复主题切换功能，确保所有主题正常工作');
      }
    }

    // 基于工具测试结果的建议
    if (testResults.utils && testResults.utils.passed < testResults.utils.total) {
      recommendations.push('🔧 检查工具函数实现，确保所有功能正常工作');
    }

    // 性能相关建议
    const totalDuration = testResults.integration?.total_duration || 0;
    if (totalDuration > 5000) { // 超过5秒
      recommendations.push('⚡ 优化测试执行性能，减少测试运行时间');
    }

    // 如果没有具体建议，提供通用建议
    if (recommendations.length === 0) {
      recommendations.push('✅ 所有测试通过，继续保持代码质量');
      recommendations.push('📚 定期运行测试套件，确保功能稳定性');
      recommendations.push('🔄 持续改进用户体验和性能');
    }

    return recommendations;
  }

  /**
   * 生成最终测试报告
   */
  private generateFinalReport(testResults: any, summary: any, recommendations: string[]): string {
    const timestamp = new Date().toLocaleString();
    
    let report = '\n';
    report += '='.repeat(100) + '\n';
    report += '📊 DataPlexus 数据源管理功能综合测试报告\n';
    report += '='.repeat(100) + '\n';
    report += `生成时间: ${timestamp}\n`;
    report += `测试版本: DataPlexus v1.0.0\n`;
    report += `测试范围: 数据源管理功能完整性验证\n\n`;

    // 执行摘要
    report += '📋 执行摘要\n';
    report += '-'.repeat(50) + '\n';
    report += `总测试数量: ${summary.total_tests}\n`;
    report += `通过测试: ${summary.passed_tests}\n`;
    report += `失败测试: ${summary.failed_tests}\n`;
    report += `成功率: ${summary.success_rate.toFixed(1)}%\n`;
    report += `总耗时: ${(summary.total_duration / 1000).toFixed(2)}秒\n`;
    report += `整体评估: ${summary.success_rate >= 90 ? '✅ 优秀' : summary.success_rate >= 70 ? '⚠️ 良好' : '❌ 需要改进'}\n\n`;

    // 详细测试结果
    report += '📊 详细测试结果\n';
    report += '-'.repeat(50) + '\n';

    // 集成测试结果
    if (testResults.integration) {
      report += `\n🔧 前端集成测试 (${testResults.integration.passed}/${testResults.integration.total})\n`;
      testResults.integration.results.forEach((test: any, index: number) => {
        report += `  ${index + 1}. ${test.name}: ${test.success ? '✅' : '❌'}\n`;
        if (!test.success && test.error) {
          report += `     错误: ${test.error}\n`;
        }
      });
    }

    // 主题测试结果
    if (testResults.theme) {
      report += `\n🎨 主题适配测试 (${testResults.theme.passed}/${testResults.theme.total})\n`;
      const themeGroups = testResults.theme.results.reduce((groups: any, result: any) => {
        if (!groups[result.theme]) groups[result.theme] = [];
        groups[result.theme].push(result);
        return groups;
      }, {});

      Object.entries(themeGroups).forEach(([theme, tests]: [string, any]) => {
        report += `  【${theme}主题】\n`;
        tests.forEach((test: any, index: number) => {
          report += `    ${index + 1}. ${test.test_name}: ${test.success ? '✅' : '❌'}\n`;
          if (!test.success && test.issues.length > 0) {
            report += `       问题: ${test.issues.join('; ')}\n`;
          }
        });
      });
    }

    // 工具测试结果
    if (testResults.utils) {
      report += `\n🔧 工具功能测试 (${testResults.utils.passed}/${testResults.utils.total})\n`;
      testResults.utils.results.forEach((test: any, index: number) => {
        report += `  ${index + 1}. ${test.name}: ${test.passed ? '✅' : '❌'}\n`;
        if (!test.passed && test.error) {
          report += `     错误: ${test.error}\n`;
        }
      });
    }

    // 改进建议
    report += '\n💡 改进建议\n';
    report += '-'.repeat(50) + '\n';
    recommendations.forEach((rec, index) => {
      report += `${index + 1}. ${rec}\n`;
    });

    // 结论
    report += '\n🎯 测试结论\n';
    report += '-'.repeat(50) + '\n';
    if (summary.success_rate >= 90) {
      report += '✅ DataPlexus数据源管理功能已准备就绪，可以投入生产使用。\n';
      report += '   所有核心功能测试通过，性能和用户体验符合预期。\n';
    } else if (summary.success_rate >= 70) {
      report += '⚠️ DataPlexus数据源管理功能基本可用，但建议修复失败的测试项。\n';
      report += '   核心功能正常，但部分细节需要优化。\n';
    } else {
      report += '❌ DataPlexus数据源管理功能存在重要问题，需要修复后再投入使用。\n';
      report += '   请优先解决失败的测试项，确保功能稳定性。\n';
    }

    report += '\n' + '='.repeat(100) + '\n';
    report += '报告结束\n';
    report += '='.repeat(100) + '\n';

    return report;
  }

  /**
   * 保存测试报告到本地存储
   */
  saveReportToStorage(report: string): void {
    try {
      const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
      const reportKey = `datasource_test_report_${timestamp}`;
      
      localStorage.setItem(reportKey, report);
      localStorage.setItem('latest_datasource_test_report', report);
      
      console.log(`📄 测试报告已保存到localStorage: ${reportKey}`);
      message.success('测试报告已保存到本地存储');
    } catch (error: any) {
      console.error('保存测试报告失败:', error);
      message.error('保存测试报告失败');
    }
  }

  /**
   * 导出测试报告为文本文件
   */
  exportReportAsFile(report: string): void {
    try {
      const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
      const filename = `DataPlexus_数据源管理_测试报告_${timestamp}.txt`;
      
      const blob = new Blob([report], { type: 'text/plain;charset=utf-8' });
      const url = URL.createObjectURL(blob);
      
      const link = document.createElement('a');
      link.href = url;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      URL.revokeObjectURL(url);
      
      console.log(`📄 测试报告已导出: ${filename}`);
      message.success('测试报告已导出为文件');
    } catch (error: any) {
      console.error('导出测试报告失败:', error);
      message.error('导出测试报告失败');
    }
  }
}

// 导出测试运行器
export default ComprehensiveTestRunner;

// 在开发环境下将测试运行器挂载到window对象
if (process.env.NODE_ENV === 'development') {
  (window as any).ComprehensiveTestRunner = ComprehensiveTestRunner;
  console.log('🔧 综合测试运行器已挂载到 window.ComprehensiveTestRunner');
  
  // 提供快捷运行方法
  (window as any).runDataSourceTests = async () => {
    const runner = new ComprehensiveTestRunner();
    const results = await runner.runAllTestSuites();
    
    // 自动保存和导出报告
    runner.saveReportToStorage(results.final_report);
    
    console.log('\n📄 完整测试报告:');
    console.log(results.final_report);
    
    return results;
  };
  
  console.log('🚀 快捷测试命令: window.runDataSourceTests()');
}
